package com.commerce.addressbook.adapter;


import android.app.Dialog;
import android.content.Context;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;


import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.commerce.addressbook.Entity.Contacts;
import com.commerce.addressbook.Entity.DataBean;
import com.commerce.addressbook.GlobalVariable;
import com.commerce.addressbook.R;
import com.commerce.addressbook.activity.MainActivity;
import com.commerce.addressbook.utlis.MyContentResolver;
import com.commerce.addressbook.utlis.ToIntent;
import com.yanzhenjie.recyclerview.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.SwipeMenuLayout;


import org.litepal.LitePal;

import java.io.File;
import java.util.List;

import static android.content.Context.INPUT_METHOD_SERVICE;

public class ExpandableAdapter extends BaseExpandableListAdapter implements View.OnClickListener  {

    //一级菜单数据源
    private List<Contacts> mParents = null;

    //二级菜单数据源
    private List<List<DataBean>> mChildren = null;

    //上下文
    private Context context;

    private InputMethodManager imm = null;

    //防止为空标记
    private int flg = 0;

    MainActivity.OnSelectedListener mOnSelectedListener;

    private Dialog bottomDialog;

    public ExpandableAdapter(Context context, List<Contacts> mParents, List<List<DataBean>> mChildren, MainActivity.OnSelectedListener mOnSelectedListener) {
        this.context = context;
        this.mOnSelectedListener = mOnSelectedListener;
        this.mParents=mParents;
        this.mChildren = mChildren;
        imm =(InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE);
    }

    @Override
    public int getGroupCount() {
        return mParents.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return mChildren.get(groupPosition).size()-1;
    }

    @Override
    public Object getGroup(int groupPosition) {
        return null;
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return null;
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.picture_selector_take_photo_btn:
                if(null != mOnSelectedListener) {
                    mOnSelectedListener.OnSelected(v, 0);
                    bottomDialog.cancel();
                }
                break;
            case R.id.picture_selector_pick_picture_btn:
                if(null != mOnSelectedListener) {
                    mOnSelectedListener.OnSelected(v, 1);
                    bottomDialog.cancel();
                }
                break;
            case R.id.picture_selector_cancel_btn:
                     bottomDialog.cancel();
                break;
        }
    }


    private class ViewHolderG{
        ImageView image;
        TextView text;
    }

    private class ViewHolderC{
        Button btn;
        SwipeMenuLayout ll;
        ImageView image;
        ImageView img;
        ImageView iv;
        EditText text;
    }

    @Override
    public View getGroupView(final int i, boolean isExpanded, View view, ViewGroup parent) {
        ViewHolderG viewHolder;
        if (view == null) {
            LayoutInflater from = LayoutInflater.from(parent.getContext());
            view = from.inflate(R.layout.group_view, null);
            viewHolder = new ViewHolderG();
            viewHolder.text = view.findViewById(R.id.contacts_name);
            viewHolder.image = view.findViewById(R.id.contacts_img);
            view.setTag(viewHolder);
        }else {
            viewHolder = (ViewHolderG) view.getTag();
        }
        viewHolder.text.setText(mParents.get(i).getContacts());
        //判断图片地址是否存在
        if(mParents.get(i).getImgUrl()==null){
            Glide.with(parent.getContext()).load(R.drawable.lxr)
                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    .into(viewHolder.image);
        }else {
            Glide.with(parent.getContext()).load(mParents.get(i).getImgUrl())
                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    .into(viewHolder.image);
        }

        viewHolder.image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Contacts contacts = mParents.get(i);
                //传入单例中
                GlobalVariable.getGlobalVariable().setContacts(contacts);
                //图片替换对话框
                show();
            }
        });
        return view;
    }

    @Override
    public View getChildView(final int i, final int i1, boolean isLastChild, View view, final ViewGroup parent) {
        final ViewHolderC viewHolder;
        if (view == null) {
            LayoutInflater inflater = LayoutInflater.from(context);                      
            view = inflater.inflate(R.layout.child_view, parent,false);
            viewHolder = new ViewHolderC();
            viewHolder.text = view.findViewById(R.id.contacts_numbers);
            viewHolder.image = view.findViewById(R.id.contacts_call);
            viewHolder.img = view.findViewById(R.id.contacts_message);
            viewHolder.iv = view.findViewById(R.id.contacts_edit);
            viewHolder.ll =view.findViewById(R.id.ll_null);
            viewHolder.btn =view.findViewById(R.id.right_view);
            view.setTag(viewHolder);
        }else {
            viewHolder = (ViewHolderC) view.getTag();
        }
        //关闭菜单 防止其他子项打开时出现打开状态 
        viewHolder.ll.smoothCloseMenu();
        viewHolder.text.setText(mChildren.get(i).get(i1).getPhone());
        if(mChildren.get(i).get(i1).getaBoolean()){
            okEidt(viewHolder);
        }else if(viewHolder.text.isFocusable()){
            noEidt(viewHolder,false);
        }
        viewHolder.iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Boolean aBoolean = mChildren.get(i).get(i1).getaBoolean();
                mChildren.get(i).get(i1).setaBoolean(!aBoolean);
                if (aBoolean){
                    //更改电话
                    new MyContentResolver(context).phoneUpdate(mParents.get(i).getIds(),viewHolder.text.getText().toString().trim(),mChildren.get(i).get(i1).getPhone());
                    mChildren.get(i).get(i1).setPhone(viewHolder.text.getText().toString().trim());
                    noEidt(viewHolder,true);
                }else  {
                    okEidt(viewHolder);
                }
            }
        });
        viewHolder.image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到打电话
                new ToIntent().toIntentDIAL(context,viewHolder.text.getText().toString().trim());
            }
        });
        viewHolder.btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //内容提供器
                new MyContentResolver(context).phoneDel(mParents.get(i).getIds(),viewHolder.text.getText().toString().trim());
                //同步到单例中
                List<DataBean> dataBeans = mChildren.get(i);
                dataBeans.remove(i1);
                mChildren.remove(i);
                mChildren.add(i,dataBeans);
                viewHolder.ll.smoothCloseMenu();
                //移除号码视图
                notifyDataSetChanged();
            }
        });
        viewHolder.img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到信息
                new ToIntent().toIntentSENDTO(context,viewHolder.text.getText().toString().trim());
            }
        });
        return view;
    }
    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }
    //不可编辑状态
    private void noEidt(ViewHolderC viewHolder,Boolean b) {
        viewHolder.iv.setImageResource(R.drawable.eidt);
        //解除禁止
        viewHolder.image.setEnabled(true);
        viewHolder.img.setEnabled(true);
        viewHolder.text.setFocusable(false);
        viewHolder.text.setFocusableInTouchMode(false);
        //强制隐藏键盘
        if(b){
            imm.hideSoftInputFromWindow(viewHolder.text.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
    //可编辑状态
    private void okEidt(ViewHolderC viewHolder) {
        viewHolder.iv.setImageResource(R.drawable.trueeidt);
        //修改中禁止打电话和发短信
        viewHolder.image.setEnabled(false);
        viewHolder.img.setEnabled(false);
        viewHolder.text.setFocusableInTouchMode(true);
        viewHolder.text.setFocusable(true);
        viewHolder.text.requestFocus();
        //打开键盘
        imm.showSoftInput(viewHolder.text, InputMethodManager.SHOW_IMPLICIT);
        viewHolder.text.setSelection(viewHolder.text.length());
    }

    private void show() {
        bottomDialog = new Dialog(context, R.style.BottomDialog);
        View contentView = LayoutInflater.from(context).inflate(R.layout.dialog, null);
        bottomDialog.setContentView(contentView);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        //填满宽度
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = context.getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        //设置动画
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();
        Button takePhotoBtn = (Button) contentView.findViewById(R.id.picture_selector_take_photo_btn);
        Button pickPictureBtn = (Button) contentView.findViewById(R.id.picture_selector_pick_picture_btn);
        Button cancelBtn = (Button) contentView.findViewById(R.id.picture_selector_cancel_btn);
        // 设置按钮监听
        takePhotoBtn.setOnClickListener(this);
        pickPictureBtn.setOnClickListener(this);
        cancelBtn.setOnClickListener(this);
    }
}

